package com.example.homework09.service;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;

import com.example.homework09.R;



public class MusicHelper {
    private MediaPlayer mediaPlayer;
    private Context context;
    private final int[] musics = new int[]{R.raw.originality, R.raw.take_me_hand};

    private int musicIndex = 0;
    private boolean prepared = false;

    public MusicHelper(Context context){
        this.context = context;
        createPlayer();
    }

    private void createPlayer() {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    }
    public void play() {
        if(mediaPlayer.isPlaying())
            return;
        if(prepared){
            mediaPlayer.start();
            return;
        }
        try {
            mediaPlayer.setDataSource(context,
                    Uri.parse("android.resource://com.example.homework09/" + musics[musicIndex]));
        } catch (Exception e) {
            e.printStackTrace();
        }
        mediaPlayer.prepareAsync();
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.start();
                prepared = true;
            }
        });
    }
    public void pause() {
        if(!mediaPlayer.isPlaying())
            return;
        mediaPlayer.pause();
    }
    public void next() {
        musicIndex = (musicIndex+1) % musics.length;
        destroy();
        createPlayer();
        play();
    }

    public void destroy() {
        if(mediaPlayer == null)
            return;
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
        prepared = false;
    }
}